package com.xunfei.deepseek

import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity() {
    private val client = OkHttpClient.Builder()
        .connectTimeout(90, TimeUnit.SECONDS)
        .readTimeout(90, TimeUnit.SECONDS)
        .writeTimeout(90, TimeUnit.SECONDS)
        .build()
    private val BASE_URL = "https://api.deepseek.com" // 替换为实际API地址
    private val API_KEY = "sk-f6666b909cbe47079d4521a4282e8a23" // 替换为实际API密钥

    private lateinit var question: EditText
    private lateinit var sendReq: Button
    private lateinit var answer: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        sendReq = findViewById(R.id.sendReq)
        question = findViewById(R.id.question)
        answer = findViewById(R.id.answer)

        var req = """
            {"id":"0a8d572f-7fa8-4f5a-ace7-55df6c0a349e","object":"chat.completion","created":1751555760,"model":"deepseek-chat","choices":[{"index":0,"message":{"role":"assistant","content":"Hello! How can I assist you today? 😊"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":9,"completion_tokens":11,"total_tokens":20,"prompt_tokens_details":{"cached_tokens":0},"prompt_cache_hit_tokens":0,"prompt_cache_miss_tokens":9},"system_fingerprint":"fp_8802369eaa_prod0623_fp8_kvcache"}
        """.trimIndent()

        sendReq.setOnClickListener {
            var message: String = question.text.toString()
            if(message.isNotEmpty())
            {
                var result = sendMessage(message)
            }
        }
    }

    // 示例1：异步POST请求（推荐方式）
    fun sendMessage(message:String,aimessage:String = "You are a helpful assistant"){
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val jsonBody = """
                    {
                      "messages": [
                        {
                          "content": "$aimessage",
                          "role": "system"
                        },
                        {
                          "content": "$message",
                          "role": "user"
                        }
                      ],
                      "model": "deepseek-chat",
                      "frequency_penalty": 0,
                      "max_tokens": 2048,
                      "presence_penalty": 0,
                      "response_format": {
                        "type": "text"
                      },
                      "stop": null,
                      "stream": false,
                      "stream_options": null,
                      "temperature": 1,
                      "top_p": 1,
                      "tools": null,
                      "tool_choice": "none",
                      "logprobs": false,
                      "top_logprobs": null
                    }
                """.trimIndent()

                val response = postAsync(
                    url = "$BASE_URL/chat/completions", json = jsonBody, headers = mapOf(
                        "Content-Type" to "application/json",
                        "Accept" to "application/json",
                        "Authorization" to "Bearer $API_KEY"
                    )
                )

                withContext(Dispatchers.Main) {
                    Log.d("POST_REQUEST", "响应: $response")
                    // 更新UI或处理响应
                    val jsonObject: String = JSONObject(response).getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content")
                    answer.append(jsonObject)
                    answer.append("\n")
                }

            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    Log.e("POST_REQUEST", "请求失败: ${e.message}")
                }
            }
        }
    }

    // 异步POST请求（使用协程+OkHttp）
    suspend fun postAsync(
        url: String, json: String, headers: Map<String, String> = emptyMap()
    ): String {
        return withContext(Dispatchers.IO) {
            val mediaType = "application/json; charset=utf-8".toMediaType()
            val body = json.toRequestBody(mediaType)

            val requestBuilder = Request.Builder().url(url).post(body)

            // 添加请求头
            headers.forEach { (key, value) ->
                requestBuilder.addHeader(key, value)
            }

            val request = requestBuilder.build()

            client.newCall(request).execute().use { response ->
                if (!response.isSuccessful) throw IOException("Unexpected code $response")
                response.body?.string() ?: "{}"
            }
        }
    }
}